package com.jjzhk.common.utils;

import net.sf.cglib.reflect.FastClass;
import net.sf.cglib.reflect.FastMethod;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.lang.reflect.InvocationTargetException;

/**
 * ReflexUtils
 *
 * @author : JJZHK
 * @date : 2016-08-19
 * @comments :
 **/
public class ReflexUtils {
    private ReflexUtils(){

    }
    public static Object Invoke(Object serviceBean, String method,
                                Class<?>[] parameterTypes, Object[] parameterValues) throws InvocationTargetException {
        FastClass serviceFastClass = FastClass.create(serviceBean.getClass());
        FastMethod serviceFastMethod = serviceFastClass.getMethod(method, parameterTypes);

        return serviceFastMethod.invoke(serviceBean, parameterValues);
    }

    public static Class<?> forName(String className)
    {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> T newObject(Class<T> className)
    {
        Objenesis objenesis = new ObjenesisStd(true);
        T obj = objenesis.newInstance(className);
        return obj;
    }

    public static <T> T newObjectWithConstructor(Class<T> className)
    {
        FastClass serviceFastClass = FastClass.create(className);
        try {
            T obj = (T)serviceFastClass.getConstructor(new Class[]{className}).newInstance();

            return obj;
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }
}
